<template>
  <el-select
    v-model="Model"
    v-bind="$attrs"
    v-on="$listeners"
    style="width: -webkit-fill-available"
    @clear="clear"
    @visible-change="visibleChange"
    :placeholder="placeholder"
  >
    <template #empty>
      <div style="width: 750px; margin: 10px">
        <EvForm
          v-bind="$attrs"
          ref="dataSourceForm"
          :itemStyle="{ marginRight: '2%', marginBottom: '10px', width: '100%' }"
          :autoWidth="false"
          @autoEmit="handleQuery"
        >
        </EvForm>
        <EvTable
          :options="{
            data: data,
            columns,
            height: '320px',
            toolbarConfig: {
              custom: false,
              slots: {
                buttons: 'toolbar_buttons',
              },
            },
            radioConfig: {
              checkMethod: checkMethod,
              trigger: 'row',
            },
          }"
          :tablePage="page"
          :showCount="false"
          @changeEvent="handleModelChange"
          @handlePageChange="handlePageChange"
          ref="EvTable"
        >
        </EvTable>
      </div>
    </template>
  </el-select>
</template>

<script>
export default {
  props: {
    value: {
      type: [String, Number, Array],
    },
    columns: {
      type: Array,
      default: () => [],
    },
    fieldValue: String,
    fieldLabel: String,
    fieldLock: {
      type: Array,
      default: () => [],
    },
    microservices: {
      type: String,
      default: "",
    },
    resource: {
      type: String,
      default: "",
    },
    placeholder: {
      type: String,
      default: "",
    },
  },
  mounted() {
    this.handleQuery();
  },
  beforeDestroy() {
    console.log("beforeDestroy");
    this.data = [];
  },
  data() {
    return {
      selectedModel: this.value,
      selectedValue: null,
      page: {
        currentPage: 1,
        pageSize: 5,
        total: 0,
      },
      searchQueries: {},
      Model: "",
      data: [],
      setRadioRow: {},
    };
  },
  watch: {
    selectedModel(newVal) {
      this.$emit("input", newVal);
    },
  },
  methods: {
    checkMethod({ row }) {
      for (let i = 0; i < this.fieldLock.length; i++) {
        if (!this.getValueFromObject(row, this.fieldLock[i])) {
          return false;
        }
      }
      return true;
    },
    visibleChange(visible) {
      if (visible) {
        this.$refs.dataSourceForm.resetFields();
        this.handleQuery();
      }
    },
    clear() {
      this.$refs.EvTable.clearRadioRow();
    },
    handleQuery() {
      this.page.currentPage = 1;
      this.searchQueries = { AND: [] };
      this.$attrs.dataSourceFormOptions.dataSourceFormItems.forEach((item) => {
        const { model, type, dateType, notUse } = item; // 添加 dateType
        const value = this.getValueByModel(model);

        if (value !== null && value !== undefined && value !== "") {
          let query;

          if (notUse) {
            return;
          }

          switch (type) {
            case "input":
              query = [model, "LIKE", `%${value}%`];
              break;
            case "select":
              query = [model, "=", value];
              break;
            case "date":
              if (dateType === "daterange") {
                query = [model, "BETWEEN '%s' AND '%s'", value]; // 修改为 BETWEEN 操作符
              } else {
                query = [model, ">", value];
              }
              break;
            // 添加其他类型的处理逻辑
          }
          this.searchQueries.AND.push(query);
        }
      });

      // 添加公共条件
      this.searchQueries.AND.push(["isDelete", "=", 0]);
      this.page.currentPage = 1;
      this.loadData();
    },
    getValueByModel(model) {
      const keys = model.split(".");
      let value = this.$attrs.dataSourceFormOptions.dataSourceForm;

      keys.forEach((key) => {
        // 检查是否为对象类型
        if (typeof value === "object" && value !== null) {
          value = value[key];
        } else {
          value = null;
        }
      });

      return value;
    },
    getValueFromObject(obj, path) {
      const keys = path.split(".");
      let value = obj;

      for (const key of keys) {
        if (value && typeof value === "object") {
          value = value[key];
        } else {
          value = undefined;
          break;
        }
      }

      return value;
    },
    handlePageChange({ currentPage, pageSize }) {
      this.page.currentPage = currentPage;
      this.page.pageSize = pageSize;
      this.loadData();
    },
    loadData() {
      this.$server()
        .query(
          this.microservices,
          this.resource,
          this.searchQueries,
          null,
          { current: this.page.currentPage, size: this.page.pageSize },
          true
        )
        .then((response) => {
          this.page.total = response.total;
          this.data = response.list;
          this.$emit("optionSet", this.data);
          if (!this.Model) {
            this.Model = this.getValueFromObject(
              this.data?.filter((item) => this.getValueFromObject(item, this.fieldValue) === this.value)[0],
              this.fieldLabel
            );
          }
          this.setRadioRow = this.data?.filter(
            (item) => this.getValueFromObject(item, this.fieldValue) === this.value
          )[0];
          this.$refs.EvTable.setRadioRow(this.setRadioRow);
        })
        .catch((response) => {
          this.$message.error(response.data.message);
        });
    },
    handleModelChange(data) {
      const fieldLabelValue = this.getValueFromObject(data, this.fieldLabel);
      const fieldValueValue = this.getValueFromObject(data, this.fieldValue);

      if (fieldLabelValue !== undefined) {
        this.Model = fieldLabelValue;
      }

      if (fieldValueValue !== undefined) {
        this.selectedModel = fieldValueValue;
        this.selectedValue = fieldValueValue;
      }

      this.$emit("input", this.selectedValue);
      this.$emit("change", this.selectedValue);
      this.$emit("selectData", data);
    },
  },
};
</script>
